<?php

declare(strict_types=1);


namespace App\Resource\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use App\Resource\Service\CartService;
use App\Resource\Service\CrdCartService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;

/**
 * @Controller()
 */
class CartController extends AbstractController
{
    /**
     * @Inject()
     * @var CartService
     */
    private $cartService;
    /**
     * @Inject()
     * @var CrdCartService
     */
    private $crdCartService;

    /**
     * 根据商品id更新购物车信息
     * @RequestMapping(path="/v1/api/cart_update/{id:\d+}", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     * @param RequestInterface $request
     * @return array
     * @throws \Exception
     */
    public function cartUpdateByGoodsId(int $id, RequestInterface $request)
    {
        $params = $request->all();
        $goodsId = $id;
        $shop_id = (int)$params['shop_id'];
        $mid = $request->getAttribute('mid');
        $num = (int)$params['num'] ?? 0;
        $isSelected = (int)$params['is_selected'] ?? 0;
        $group_id = (int)$params['group_id'] ?? 0;
        $activityGoodsId = (int)$params['activity_goods_id'] ?? 0;
        if (!$goodsId || !$shop_id || !$mid) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $updateOrAddData = ['goods_num' => $num, 'is_selected' => $isSelected];
        $cartRes = $this->cartService->setInfoGoodsId($mid, $goodsId, $updateOrAddData, $group_id, $shop_id,$activityGoodsId);
        if (!$cartRes['code']) {
            return $this->success('', '更新购物车成功');
        } else {
            return $this->failed($cartRes['code']);
        }
    }

    /**
     * 批量加入购物车
     * @RequestMapping(path="/v1/api/cart_batch", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     * @return array
     */
    public function cartBatch(RequestInterface $request)
    {
        $params = $request->all();
        $mid = $request->getAttribute('mid');
        $shop_id = (int)$params['shop_id'];
        $goodsListArr = json_decode($params['goods_list'], true);
        if (!is_array($goodsListArr)) {
            return $this->failed(ErrorCode::ERROR_TYPE);
        }
        $field = [
            'mid',
            'shop_id',
            'source',
            'group_id',
            'activity_goods_id',
            'goods_id',
            'goods_num',
            'is_selected'
        ];
        $res = $this->cartService->batchCart($mid, $shop_id, $goodsListArr, $field);
        if (!$res['code']) {
            return $this->success('', '加入购物车成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 购物车全选/反全选
     * @RequestMapping(path="/v1/api/cart_check", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     * @return array
     */
    public function cartCheck(RequestInterface $request)
    {
        $params = $request->all();
        $isSelected = $params['is_selected']; //购物车勾选的状态 0未勾选 1、勾选
        $mid = $request->getAttribute('mid');
        $shop_id = (int)$params['shop_id'];
        if (!$shop_id || !$mid) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $field = [
            'mid',
            'shop_id',
            'goods_id',
            'goods_num',
            'is_selected'
        ];
        $cartList = $this->cartService->cartList(['mid' => $mid,'shop_id' => $shop_id], $field);
        $goodsId = array_column($cartList, 'goods_id');
        $updateOrAddData = ['is_selected' => $isSelected, 'update_at' => date('Y-m-d H:i:s')];
        if(!empty($cartList)){
            $this->cartService->setInfoByCartCheck($mid, $shop_id, $goodsId, $updateOrAddData);
        }
        return $this->success('','成功');

    }

    /**
     * 清空购物车
     * @RequestMapping(path="/v1/api/cart_clear", methods="delete")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     * @return array
     */
    //需加上shop_id情况当前门店的购物车
    public function clearCartAll(RequestInterface $request)
    {
        $params = $request->all();
        $mid = $request->getAttribute('mid');
        $shop_id = (int)$params['shop_id'];
        if (!$mid || !$shop_id) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $cartDel = $this->cartService->deleteCart(['mid' => $mid,'shop_id' => $shop_id,'source'=>1]);
        if (!$cartDel) {
            return $this->failed(ErrorCode::CART_CLEAR_FAIL);
        }
        return $this->success('', '购物车已清空');
    }

    /**
     * 清空购物车无效商品
     * @RequestMapping(path="/v1/api/cartfail_clear", methods="delete")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     * @return array
     */
    public function clearCartNoGoods(RequestInterface $request)
    {
        $params = $request->all();
        $mid = $request->getAttribute('mid');
        $shop_id = (int)$params['shop_id'];
        if (!$shop_id || !$mid) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->cartService->deleteNoCart($shop_id, $mid);
        $tomorrowRes = $this->crdCartService->deleteNoCart($shop_id, $mid);
        if ($res||$tomorrowRes) {
            return $this->success('', '无效商品已清空');
        } else {
            return $this->failed(ErrorCode::CART_CLEAR_FAIL);
        }

    }

    /**
     * 购物车列表 、结算购物车列表
     * @RequestMapping(path="/v1/api/cart_list", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     * @return array
     */
    public function getCartList(RequestInterface $request)
    {
        $params = $request->all();
        $mid = $request->getAttribute('mid');
        $shop_id = (int)$params['shop_id'];
        if (!$shop_id || !$mid) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $field = [
            'id',
            'mid',
            'goods_id',
            'goods_num',
            'is_selected',
            'activity_goods_id',
            'group_id',
            'source'
        ];
        $cartList = $this->cartService->cartList(['mid' => $mid,'shop_id'=>$shop_id,'source'=>1], $field);
        $tomorrowCartList = $this->cartService->cartList(['mid' => $mid,'shop_id'=>$shop_id,'source'=>2], $field);
        $goodsId = array_column($cartList, 'goods_id');
        $tomorrowGoodsId = array_column($tomorrowCartList, 'goods_id');
        //获取最新购物车列表
        $cartList = $this->cartService->getCartListArr($cartList, $tomorrowCartList, $goodsId, $tomorrowGoodsId, $shop_id, $mid);
        if ($cartList) {
            return $this->success($cartList);
        } else {
            return $this->failed(ErrorCode::NOT_EXIST);
        }
    }

    /**
     * 购物车选中数量商品
     * @RequestMapping(path="/v1/api/cart_goods_number", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    //加传shop_id
    public function cartNumber(RequestInterface $request)
    {
        $params = $request->all();
        $mid = (int)$params['mid'];
        $shop_id = (int)$params['shop_id'];
        if (!$shop_id || !$mid) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $total = $this->cartService->cartGoodsNumber($mid,$shop_id);
        return $this->success([], '', $total);
    }
}
